//
//  ARMineViewController.swift
//  AquaRaft
//
//  Created by 何启亮 on 2024/4/2.
//

import UIKit
import SnapKit
import JKSwiftExtension
import Kingfisher
import MJRefresh

class ARMineViewController: ARBaseViewController {

    // MARK: - Property
    
    /// 记录所有的actionBtn
    private var actionBtns: [ARMineOperationView] = []
    
    private var viewModel = ARMineViewModel()
    
    // MARK: - Init
    
    override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
        super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
        
        self.fd_prefersNavigationBarHidden = true
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    // MARK: - LifeCycle
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        setupUI()
        refreshData()
        
        NotificationCenter.default.addObserver(self, selector: #selector(updateValue), name: .userInfoUpdate, object: nil)
    }
    
    // MARK: - UI
    
    private func setupUI() {
        
        // 这个值是topImageView / contentBgView 交汇的高度
        let padding = 36.0
        let topImageView = UIImageView(image: .init(named: "mine_top_content_bg"))
        let contentBgView = UIImageView(image: .init(named: "mine_content_bg")?.resizableImage(withCapInsets: .init(top: padding, left: 20, bottom: 20, right: 20), resizingMode: .stretch))
        
        let takePhotoImgView = UIImageView(image: .init(named: "mine_takePhoto_icon"))
        
        self.view.addSubview(scrollView)
        self.view.addSubview(navView)
        scrollView.addSubview(topImageView)
        scrollView.addSubview(balancesView)
        scrollView.addSubview(contentBgView)
        
        scrollView.addSubview(avatarBtn)
        scrollView.addSubview(takePhotoImgView)
        scrollView.addSubview(nicknameLabel)
        scrollView.addSubview(nameEditBtn)
        scrollView.addSubview(idLabel)
        scrollView.addSubview(copyBtn)
        
        navView.snp.makeConstraints { make in
            make.left.right.equalToSuperview()
            make.height.equalTo(44)
            make.top.equalToSuperview().offset(ARHelper.statusBarHeight())
        }
        
        scrollView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
        
        // 计算高度
        let width = ARHelper.screenWidth()
        let topImgHeight = width * (304.0 / 375.0)
        // 最少高度 - 屏幕高度 - topImage 高度，剩余的高度
        // 真实高度由内容决定
        let contentMinHeight = ARHelper.screenHeight() - topImgHeight + padding
        
        topImageView.snp.makeConstraints { make in
            make.top.left.right.equalToSuperview()
            make.height.equalTo(topImgHeight)
            make.width.equalTo(width)
        }
        
        contentBgView.snp.makeConstraints { make in
            make.bottom.left.right.equalToSuperview()
            make.height.greaterThanOrEqualTo(contentMinHeight)
            make.top.equalTo(topImageView.snp.bottom).offset(-padding)
        }
        
        balancesView.snp.makeConstraints { make in
            make.centerX.equalToSuperview()
            make.bottom.equalTo(topImageView).offset(-5)
        }
        
        avatarBtn.snp.makeConstraints { make in
            make.width.height.equalTo(64)
            make.left.equalToSuperview().offset(20)
            make.top.equalToSuperview().offset(48 + ARHelper.statusBarHeight())
        }
        
        takePhotoImgView.snp.makeConstraints { make in
            make.right.equalTo(avatarBtn.snp.right)
            make.bottom.equalTo(avatarBtn.snp.bottom)
        }
        
        nicknameLabel.snp.makeConstraints { make in
            make.height.equalTo(20)
            make.top.equalTo(avatarBtn).offset(8)
            make.left.equalTo(avatarBtn.snp.right).offset(16)
        }
        
        nameEditBtn.snp.makeConstraints { make in
            make.centerY.equalTo(nicknameLabel)
            make.left.equalTo(nicknameLabel.snp.right).offset(8)
        }
        
        idLabel.snp.makeConstraints { make in
            make.height.equalTo(14)
            make.top.equalTo(nicknameLabel.snp.bottom).offset(18)
            make.left.equalTo(nicknameLabel)
        }
        
        copyBtn.snp.makeConstraints { make in
            make.centerY.equalTo(idLabel)
            make.left.equalTo(idLabel.snp.right).offset(8)
            make.width.equalTo(35)
            make.height.equalTo(12)
        }
        
        // 添加actions
        var lastView: UIView?
        for (index, action) in viewModel.dataSource.enumerated() {
            let (icon, title) = action.value()
            let view = ARMineOperationView(type: .custom)
            view.addTarget(self, action: #selector(actionBtnClicked(_:)), for: .touchUpInside)
            view.iconView.ar.setImage(icon)
            view.textLabel.text = title
            
            scrollView.addSubview(view)
            actionBtns.append(view)
            
            view.snp.makeConstraints { make in
                make.left.equalToSuperview().offset(27)
                make.right.equalToSuperview().offset(-27)
                make.height.equalTo(64)
                if let lastView = lastView {
                    make.top.equalTo(lastView.snp.bottom).offset(16)
                } else {
                    make.top.equalTo(contentBgView).offset(32)
                }
                // 最后一个
                if index == viewModel.dataSource.count - 1 {
                    make.bottom.equalTo(contentBgView).offset(-(45 + ARHelper.tabBarHeight() + ARHelper.safeBottomHeight()))
                }
            }
            
            lastView = view
        }
    }
    
    // MARK: Value
    
    // 主动刷新值
    @objc private func updateValue() {
        guard let userModel = ARUserManager.shared.userModel else {
            return
        }
        let avatarStr = userModel.trueAvatar
        if let url = URL(string: avatarStr) {
            avatarBtn.kf.setImage(with: url, for: .normal)
        }
        nicknameLabel.text = userModel.nickname
        idLabel.text = "ID: \(userModel.userId)"
        balancesView.balanceLabel.text = String(userModel.availableCoins ?? 0)
    }
    
    // MARK: - Action
    
    @objc private func actionBtnClicked(_ sender: ARMineOperationView) {
        guard let index = actionBtns.firstIndex(sender) else {
            return
        }
        let operation = viewModel.dataSource[index]
        switch operation {
        case .gifts(_, _):
            let vc = ARMyGiftController()
            self.navigationController?.pushViewController(vc, animated: true)
        case .recommendation(_, _):
            let vc = ARMineRecommendationController()
            self.navigationController?.pushViewController(vc, animated: true)
            break
        case .articles(_, _):
            let vc = ARMyArticlesController()
            self.navigationController?.pushViewController(vc, animated: true)
            break
        case .follow(_, _):
            let vc = ARMineBlockLIstOrFollowListController(operationType: .followList)
            self.navigationController?.pushViewController(vc, animated: true)
            break
        case .blackList(_, _):
            let vc = ARMineBlockLIstOrFollowListController(operationType: .blockList)
            self.navigationController?.pushViewController(vc, animated: true)
            break
        }
    }
    
    @objc private func settingBtnClicked(_ sender: UIButton) {
        self.navigationController?.pushViewController(ARSettingViewContrtoller(), animated: true)
    }
    
    @objc private func aboutBtnClicked(_ sender: UIButton) {
        self.navigationController?.pushViewController(ARAboutController(), animated: true)
    }
    
    @objc private func avatarBtnClicked(_ sender: UIButton) {
        let vc = AREditUserInfoController()
        self.navigationController?.pushViewController(vc, animated: true)
    }
    
    @objc private func nameEditBtnClicked(_ sender: UIButton) {
        let vc = AREditUserInfoController()
        self.navigationController?.pushViewController(vc, animated: true)
    }
    
    @objc private func copyIdBtnClicked(_ sender: UIButton) {
        
        guard let userId = ARUserManager.shared.userId else {
            return
        }
        
        UIPasteboard.general.string = userId
        self.ar.makeToast(ARHelper.localString("Copy successful!"))
    }
    
    // MARK: - Lazy
    
    private lazy var refreshHeader: ARRefreshHeader = {
        let header = ARRefreshHeader(refreshingTarget: self, refreshingAction: #selector(refreshData))
        header.stateLabel?.isHidden = true
        header.lastUpdatedTimeLabel?.isHidden = true
        return header
    }()
    
    private lazy var scrollView: UIScrollView = {
        let view = UIScrollView()
        view.mj_header = refreshHeader
        return view
    }()
    
    private lazy var balancesView: __ARMineCoinsView = {
        let view = __ARMineCoinsView(frame: .zero)
        view.buyBtnClickCallback = { [weak self] in
            let vc = ARBalanceRechargeController()
            self?.navigationController?.pushViewController(vc, animated: true)
        }
        return view
    }()
    
    private lazy var navView: UIView = {
        let view = UIView()
        view.backgroundColor = .clear
        
        let settingBtn = UIButton(type: .custom)
        settingBtn.addTarget(self, action: #selector(settingBtnClicked(_:)), for: .touchUpInside)
        settingBtn.setImage(.init(named: "mine_setting"), for: .normal)
        
        let aboutBtn = UIButton(type: .custom)
        aboutBtn.addTarget(self, action: #selector(aboutBtnClicked(_:)), for: .touchUpInside)
        aboutBtn.setImage(.init(named: "mine_about"), for: .normal)
        
        view.addSubview(settingBtn)
        view.addSubview(aboutBtn)
        
        settingBtn.snp.makeConstraints { make in
            make.centerY.equalToSuperview()
            make.right.equalToSuperview().offset(-20)
        }
        
        aboutBtn.snp.makeConstraints { make in
            make.centerY.equalToSuperview()
            make.right.equalTo(settingBtn.snp.left).offset(-24)
        }
        
        return view
    }()
    
    private lazy var avatarBtn: UIButton = {
        let btn = UIButton(type: .custom)
        btn.addTarget(self, action: #selector(avatarBtnClicked(_:)), for: .touchUpInside)
        btn.layer.cornerRadius = 32
        btn.layer.masksToBounds = true
        btn.layer.borderColor = UIColor.white.cgColor
        btn.layer.borderWidth = 2
        return btn
    }()
    
    private lazy var nicknameLabel: UILabel = {
        let nameLabel = UILabel()
        nameLabel.font = ARHelper.font(18, weight: .medium)
        nameLabel.textColor = .white
        return nameLabel
    }()
    
    private lazy var nameEditBtn: UIButton = {
        let btn = UIButton(type: .custom)
        btn.addTarget(self, action: #selector(nameEditBtnClicked(_:)), for: .touchUpInside)
        btn.setImage(.init(named: "mine_edit"), for: .normal)
        return btn
    }()
    
    private lazy var idLabel: UILabel = {
        let nameLabel = UILabel()
        nameLabel.font = ARHelper.font(14, weight: .regular)
        nameLabel.textColor = .white.withAlphaComponent(0.5)
        return nameLabel
    }()
    
    private lazy var copyBtn: UIButton = {
        let btn = UIButton(type: .custom)
        btn.addTarget(self, action: #selector(copyIdBtnClicked(_:)), for: .touchUpInside)
        btn.setTitle(ARHelper.localString("Copy"), for: .normal)
        btn.backgroundColor = UIColor(hexString: "#AFD8FF")
        btn.setTitleColor(.white, for: .normal)
        btn.layer.cornerRadius = 6
        btn.titleLabel?.font = ARHelper.font(10, weight: .regular)
        return btn
    }()
}

fileprivate class __ARMineCoinsView: UIView {
    
    var buyBtnClickCallback: (() -> Void)?
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        setupUI()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupUI() {
        // 叠几层渐变
        // #A0F9FF #4C89FF
        // #F3FCB9 #B1FFC2
        // effect view
        
        let size = intrinsicContentSize
        let midView = UIImageView(image: UIImage.jk.gradient(["#A0F9FF", "#4C89FF"], size: size))
        let bottomView = UIImageView(image: UIImage.jk.gradient(["#F3FCB9", "#B1FFC2"], size: size))
        midView.alpha = 0.8
        self.addSubview(bottomView)
        self.addSubview(midView)
        self.jk.effectViewWithAlpha(alpha: 0.5, size: size, style: .dark)
        
        self.layer.cornerRadius = 16
        self.layer.masksToBounds = true
        
        let coinIconView = UIImageView(image: .init(named: "common_coin_icon"))
        let titleLabel = UILabel()
        titleLabel.font = ARHelper.font(12, weight: .regular)
        titleLabel.textColor = UIColor(hexString: "#565656")
        titleLabel.text = ARHelper.localString("My Coins")
        
        self.addSubview(coinIconView)
        self.addSubview(titleLabel)
        self.addSubview(buyBtn)
        self.addSubview(balanceLabel)
        
        coinIconView.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(ARHelper.widthScale(23.0))
            make.width.equalTo(60)
            make.height.equalTo(53)
            make.top.equalToSuperview().offset(ARHelper.heightScale(19))
        }
        
        titleLabel.snp.makeConstraints { make in
            make.left.equalTo(coinIconView.snp.right).offset(10)
            make.top.equalToSuperview().offset(ARHelper.heightScale(30))
        }
        
        balanceLabel.snp.makeConstraints { make in
            make.left.equalTo(titleLabel)
            make.top.equalTo(titleLabel.snp.bottom).offset(4)
        }
        
        buyBtn.snp.makeConstraints { make in
            make.width.equalTo(66)
            make.height.equalTo(24)
            make.right.equalToSuperview().offset(ARHelper.widthScale(-26))
            make.top.equalToSuperview().offset(ARHelper.heightScale(32))
        }
        
        balanceLabel.text = "10000"
    }
    
    override var intrinsicContentSize: CGSize {
        let width = ARHelper.screenWidth() - 22 * 2
        let height = width * 110.0 / 331.0
        return .init(width: width, height: height)
    }
    
    private lazy var buyBtn: UIButton = {
        let btn = UIButton(type: .custom)
        btn.titleLabel?.font = ARHelper.font(16, weight: .regular)
        btn.setTitle(ARHelper.localString("Buy"), for: .normal)
        btn.setTitleColor(.init(hexString: "#4DB4FF"), for: .normal)
        btn.layer.cornerRadius = 13
        btn.backgroundColor = .white
        btn.jk.setHandleClick { [weak self] button in
            self?.buyBtnClickCallback?()
        }
        return btn
    }()
    
    lazy var balanceLabel: UILabel = {
        let label = UILabel()
        label.font = ARHelper.font(16, weight: .heavy)
        label.textColor = .init(hexString: "#1F1C1C")
        return label
    }()
    
}

extension ARMineViewController: ARTabControllerRefresh {
    @objc func refreshData() {
        
        // 刷新
        if let userId = ARUserManager.shared.userId {
            
            if self.refreshHeader.isRefreshing == false {
                self.ar.showLoading()
            }
            ARUserManager.shared.fetchMineUserInfo(userId) { [weak self] err in
                self?.ar.hideHUD()
                self?.refreshHeader.endRefreshing()
                if let err = err {
                    self?.ar.makeToast(err.localizedDescription)
                    return
                }
                
                // 刷新
                self?.updateValue()
            }
        }
    }
}
